package com.zhuyi.broadcast.controller;

import com.zhuyi.broadcast.pojo.domain.Element;
import com.zhuyi.broadcast.pojo.domain.ElementResourceRelation;
import com.zhuyi.broadcast.pojo.domain.ProgramElementRelation;
import com.zhuyi.broadcast.pojo.domain.Resource;
import com.zhuyi.broadcast.service.ElementService;
import com.zhuyi.broadcast.service.ProgramService;
import com.zhuyi.common.annotation.Log;
import com.zhuyi.common.core.controller.BaseController;
import com.zhuyi.common.core.domain.AjaxResult;
import com.zhuyi.common.core.page.TableDataInfo;
import com.zhuyi.common.enums.BusinessType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;


/**
 * <p>
 *  元素Controller
 * </p>
 *
 * @author dyj
 * @since 2024-12-12
 */
@RestController
@RequestMapping("/broadcast")
public class ElementController extends BaseController {

    @Autowired
    private ElementService elementService;

    @Autowired
    private ProgramService programService;

    /**
     * 查询元素（列表）
     */
    @GetMapping("/element/list")
    public TableDataInfo listAvailableElements(Element element) {

        //分页功能
        startPage();

        //查询元素列表
        List<Element> list = elementService.selectAvailableElements(element);

        //返回分页后的数据
        return getDataTable(list);
    }

    /**
     * 查询元素（节目中列表）
     */
    @GetMapping("/program/elementslist")
    public AjaxResult getElementsList(@RequestBody Map<String, Long> programInfo) {
        Long programId = programInfo.get("programId");
        if (programId == null) {
            return error("Program ID is required");
        }

        // 获取已选择的元素列表
        List<ProgramElementRelation> selectedElements = elementService.getElementsListByProgramId(programId);
        return success(selectedElements);
    }

    /**
     * 查询元素（节目中单个）
     * @param params 请求体中的参数
     * @return AjaxResult 返回元素详细信息
     */
    @GetMapping("/program/element/{elementId}")
    public AjaxResult getElementDetails(@RequestBody Map<String, Long> params,
                                        @PathVariable Long elementId) {
        Long programId = params.get("programId");

        // 参数检查
        if (programId == null || elementId == null) {
            return error("Program ID and Element ID are required");
        }

        // 获取元素详细信息
        ProgramElementRelation programElementRelation = elementService.getElementByProgramId(programId, elementId);
        if (programElementRelation == null) {
            return error("Element not found");
        }

        return success(programElementRelation);
    }

    /**
     * 添加元素（到节目）
     */
    @Log(title = "元素", businessType = BusinessType.INSERT)
    @PostMapping("/program/element")
    public AjaxResult addElementToProgram(@RequestParam Long programId,
                                          @RequestParam Long elementId) {
        boolean success = elementService.addElementToProgram(programId,elementId);
        return success ? success("元素添加成功") : error("元素添加失败");
    }

    /**
     * 保存元素（设置为可见）
     */
    @Log(title = "元素", businessType = BusinessType.INSERT)
    @PostMapping("/element/{elementId}}")
    public AjaxResult saveElement(@PathVariable Long elementId) {
        boolean success = elementService.saveElement(elementId);
        return success ? success("元素保存成功") : error("元素保存失败");
    }

    /**
     * 添加元素（到列表）
     */
    @Log(title = "元素", businessType = BusinessType.INSERT)
    @PostMapping("/element")
    public AjaxResult add(@RequestBody Element element) {
        element.setElementName("未命名元素");
        element.setHideFlag(1);
        return toAjax(elementService.save(element));
    }

    /**
     * 删除元素（仅从当前节目中删除，不删除资源本身）
     */
    @Log(title = "元素", businessType = BusinessType.DELETE)
    @DeleteMapping("/program/element")
    public AjaxResult removeElementFromProgram(@RequestBody Map<String, Long> params) {
        Long programId = params.get("programId");
        Long elementId = params.get("elementId");

        boolean success = elementService.removeElementFromProgram(programId, elementId);
        return success ? success("元素删除成功") : error("元素删除失败");
    }

    /**
     * 删除元素（彻底删除）
     */
    @Log(title = "元素", businessType = BusinessType.DELETE)
    @DeleteMapping("/element/{elementId}")
    public AjaxResult removeElement(@PathVariable Long elementId) {
        boolean success = elementService.removeElement(elementId);
        return success ? success("元素删除成功") : error("元素删除失败");
    }

    /**
     * 更新元素(指定节目中)
     * @param params 请求体中的参数
     * @return AjaxResult 返回更新后的元素信息
     */
    @PutMapping("/program/element")
    public AjaxResult updateElement(@RequestBody Map<String, String> params) {
        Long programId = Long.valueOf(params.get("programId"));
        Long elementId = Long.valueOf(params.get("elementId"));

        // 参数检查
        if (programId == null || elementId == null) {
            return error("Program ID and Element ID are required");
        }

        // 更新元素
        boolean result = elementService.updateElement(programId, elementId, params);
        if (!result) {
            return error("Failed to update element");
        }

        // 返回更新后的元素信息
        ProgramElementRelation updatedElement = elementService.getElementByProgramId(programId, elementId);
        return success(updatedElement);
    }

    /**
     * 添加资源（到元素）
     */
    @Log(title = "元素", businessType = BusinessType.INSERT)
    @PostMapping("/element/{elementId}/resource")
    public AjaxResult addResourceToElement(@PathVariable Long elementId, @RequestParam Long resourceId) {
        try {
            // 调用服务层方法进行资源添加操作
            boolean success = elementService.addResourceToElement(elementId, resourceId);
            return success ? AjaxResult.success("资源添加成功") : AjaxResult.error("资源添加失败");
        } catch (Exception e) {
            return AjaxResult.error("发生异常: " + e.getMessage());
        }
    }

    /**
     * 查询资源（元素中列表）
     */
    @GetMapping("/element/resourcelist")
    public AjaxResult getResourcesList(@RequestBody Map<String, Long> elementInfo) {
        Long elementId = elementInfo.get("elementId");
        if (elementId == null) {
            return error("ElementId ID is required");
        }

        // 获取已选择的元素列表
        List<ElementResourceRelation> selectedResources = elementService.getResourcesListByElementId(elementId);
        return success(selectedResources);
    }

    /**
     * 删除资源（从元素中剔除）
     */
    @Log(title = "资源", businessType = BusinessType.DELETE)
    @DeleteMapping("/element/{elementId}/resource")
    public AjaxResult removeResourceFromElement(@RequestBody ElementResourceRelation request,
                                                @PathVariable Long elementId) {
        try {
            boolean success = elementService.removeResourceFromElement(elementId, request.getResourceId());
            return success ? AjaxResult.success("资源从元素中移除成功") : AjaxResult.error("资源从元素中移除失败");
        } catch (Exception e) {
            return AjaxResult.error("移除资源失败: " + e.getMessage());
        }
    }

    /**
     * 更新资源（元素中）
     * 针对不同类型资源进行不同的编辑操作
     */
    @PutMapping("/element/{elementId}/resource/{resourceId}")
    public String updateResource(
            @PathVariable("elementId") Long elementId,
            @PathVariable("resourceId") Long resourceId,
            @RequestBody String config) {
        boolean updated = elementService.updateResource(elementId, resourceId, config);
        return updated ? "资源配置更新成功" : "资源配置更新失败";
    }
}
